/**
 * 缓存监控工具
 * 用于监控和调试缓存重复问题
 */

export interface CacheStats {
  cacheName: string;
  modelCount: number;
  totalSize: number;
  duplicateCount: number;
  cacheHits: number;
  cacheMisses: number;
  lastUpdated: Date;
}

class CacheMonitor {
  private stats: CacheStats | null = null;
  private cacheHits = 0;
  private cacheMisses = 0;
  private duplicateRequests = new Set<string>();

  async getCacheStats(): Promise<CacheStats> {
    if (!('caches' in window)) {
      throw new Error('Cache API not supported');
    }

    const cache = await caches.open('ai-human-models-cache');
    const keys = await cache.keys();
    
    let totalSize = 0;
    const uniqueUrls = new Set<string>();
    
    for (const request of keys) {
      uniqueUrls.add(request.url);
      const response = await cache.match(request);
      if (response) {
        const blob = await response.blob();
        totalSize += blob.size;
      }
    }

    return {
      cacheName: 'ai-human-models-cache',
      modelCount: uniqueUrls.size,
      totalSize,
      duplicateCount: keys.length - uniqueUrls.size,
      cacheHits: this.cacheHits,
      cacheMisses: this.cacheMisses,
      lastUpdated: new Date()
    };
  }

  async checkDuplicateCache(): Promise<{
    duplicates: string[];
    uniqueCount: number;
    totalCount: number;
  }> {
    const cache = await caches.open('ai-human-models-cache');
    const keys = await cache.keys();
    
    const urlMap = new Map<string, number>();
    
    for (const request of keys) {
      const count = urlMap.get(request.url) || 0;
      urlMap.set(request.url, count + 1);
    }
    
    const duplicates = Array.from(urlMap.entries())
      .filter(([_, count]) => count > 1)
      .map(([url, count]) => `${url} (${count}次)`);
    
    return {
      duplicates,
      uniqueCount: urlMap.size,
      totalCount: keys.length
    };
  }

  async clearDuplicates(): Promise<number> {
    const cache = await caches.open('ai-human-models-cache');
    const keys = await cache.keys();
    
    const urlMap = new Map<string, Request[]>();
    
    // 收集重复的URL
    for (const request of keys) {
      const existing = urlMap.get(request.url) || [];
      existing.push(request);
      urlMap.set(request.url, existing);
    }
    
    let deletedCount = 0;
    
    // 删除重复项，只保留一个
    for (const [url, requests] of urlMap) {
      if (requests.length > 1) {
        // 保留第一个，删除其余的
        for (let i = 1; i < requests.length; i++) {
          await cache.delete(requests[i]);
          deletedCount++;
        }
      }
    }
    
    return deletedCount;
  }

  logCacheEvent(type: 'hit' | 'miss' | 'cache' | 'duplicate', url: string) {
    console.log(`[CacheMonitor] ${type}: ${url}`);
    
    switch (type) {
      case 'hit':
        this.cacheHits++;
        break;
      case 'miss':
        this.cacheMisses++;
        break;
      case 'duplicate':
        this.duplicateRequests.add(url);
        break;
    }
  }

  async debugCacheInfo() {
    const stats = await this.getCacheStats();
    const duplicateInfo = await this.checkDuplicateCache();
    
    console.group('🔄 缓存监控信息');
    console.log('📊 缓存统计:', {
      模型数量: stats.modelCount,
      总大小: this.formatBytes(stats.totalSize),
      重复缓存: stats.duplicateCount,
      缓存命中率: `${((stats.cacheHits / (stats.cacheHits + stats.cacheMisses)) * 100).toFixed(2)}%`,
      最后更新: stats.lastUpdated.toLocaleString()
    });
    
    if (duplicateInfo.duplicates.length > 0) {
      console.log('⚠️ 发现重复缓存:', duplicateInfo.duplicates);
    }
    
    console.groupEnd();
    
    return { stats, duplicateInfo };
  }

  private formatBytes(bytes: number): string {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }
}

// 创建全局实例
export const cacheMonitor = new CacheMonitor();

// 在开发环境中自动监控
if (process.env.NODE_ENV === 'development') {
  // 每30秒检查一次缓存状态
  setInterval(() => {
    cacheMonitor.debugCacheInfo();
  }, 30000);
  
  // 页面加载时检查
  window.addEventListener('load', () => {
    cacheMonitor.debugCacheInfo();
  });
}

// 添加到全局对象用于调试
if (typeof window !== 'undefined') {
  (window as any).cacheMonitor = cacheMonitor;
}